package com.inspur.resourcequery;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.inspur.common.BaseActivity;
import com.inspur.common.MyApplication;
import com.inspur.common.UserInfo;
import com.inspur.common.domain.RequestInfo;
import com.inspur.common.utils.JsonUtil;
import com.inspur.common.utils.URLManager;
import com.inspur.resourcequery.dbHelper.CacheService;

import droid.app.hp.api.platform.Platform;
import droid.app.hp.api.platform.Platform.PlatformCallback;
public class SearchActivity extends BaseActivity  {
	
	// 登陆人信息
	private UserInfo userInfo;
	
	private MyApplication application;
		
	private Button search_button;
	private Spinner profess_spinner;
	private Spinner netype_spinner;
	private EditText res_name_edit;
	private Spinner city_spinner;

	private ArrayList<String[]> professList;
	private ArrayList<String[]> netypesList;
	private ArrayList<String[]> citysList;

	// 单选框选择的数据
	private String professSelected;
	private String netypeSelected;
	private String citySelected;

	private ArrayList<String> pronameList;
	private ArrayList<String> provalueList;
	private ArrayList<String> netypenameList;
	private ArrayList<String> netypevalueList;
	private ArrayList<String> citynameList;
	private ArrayList<String> cityvalueList;
	
	ArrayAdapter<String> cityAdapter;
	ArrayAdapter<String> netTypeAdapter;
	ArrayAdapter<String> profAdapter;

	private Platform platform;
	private String packageName = "com.inspur.resourcequery";

	private String conditionKey = "conditionKey";
	private boolean existCacheFlag = false;
	CacheService  cacheService;
	
	
	String res_edit = "";
	
	String phone;
	String useraccount;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_search);
		application = (MyApplication)this.getApplication();
		
		// 初始化
		professList = new ArrayList<String[]>();
		citysList = new ArrayList<String[]>();
		netypesList = new ArrayList<String[]>();
		pronameList = new ArrayList<String>();
		provalueList = new ArrayList<String>();
		netypenameList = new ArrayList<String>();
		netypevalueList = new ArrayList<String>();
		citynameList = new ArrayList<String>();
		cityvalueList = new ArrayList<String>();
		
		search_button = (Button) findViewById(R.id.search_button);
		search_button.setOnClickListener(searchClickListener);
		// 数据初始化
		findViewById() ;
		
//		phone = "18735132803";
//		phone = this.getIntent().getStringExtra("phone");
		//山西用
//		useraccount = SecurityUtil.decryptKey(this.getIntent().getStringExtra("security_login_name"),"2b16de3dfd90d7b1ff328b3a8fa9e754");
		//四川
//		useraccount = SecurityUtil.decryptKey(this.getIntent().getStringExtra("security_login_name"),"553afd535955727195f66482dbbe8b");
		
	}
	
	@Override
	protected void onResume() {
		// TODO Auto-generated method stub
		super.onResume();
		// 初始化,设置回调接口
//		platform = Platform.getInstance(SearchActivity.this, callback);
		// 绑定服务
//		platform.bindService();
		
//		if(application.getUserInfo() != null){
//			userInfo = application.getUserInfo();
//			queryInitData();
//		}
//		Log.e("phone", phone);
		if(useraccount == null || "".equals(useraccount)){
			
	      try {
//	    	  PackageInfo packageInfo = this.getPackageManager().getPackageInfo("com.inspur.zsyw", 0);
	    	  PackageInfo packageInfo = this.getPackageManager().getPackageInfo("droid.app.hp", 0);
	      } catch (Exception e) {
	    	  Toast.makeText(SearchActivity.this, "用户信息验证失败！", Toast.LENGTH_SHORT).show();
			  SearchActivity.this.onBackPressed();
	          e.printStackTrace();
	      }
			
			// 初始化,设置回调接口
			platform = Platform.getInstance(SearchActivity.this, callback);
			// 绑定服务
			platform.bindService();
			
			if(application.getUserInfo() != null){
				userInfo = application.getUserInfo();
				queryInitData();
			}
		} else {
			if(application.getUserInfo() != null){
				userInfo = application.getUserInfo();
				queryInitData();
			} else{
				queryUserInfoByAccount();
			}
		}
	}

	enum Action {
		USER, URL
	}
	private Action action;
	
	PlatformCallback callback = new PlatformCallback() {

		@Override
		public void onSuccess(String response) {
			if(action == Action.USER){
				Log.e("userinfo", response);
				try {
					JSONObject jsonObject = new JSONObject(response);
					userInfo = (UserInfo)JsonUtil.fromJsonToModel(jsonObject, UserInfo.class);
					application.setUserInfo(userInfo);
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				action = Action.URL;
				platform.getBaseUrl(packageName);
			} else if (action == Action.URL) {
				//如果URl最后带有“/”符号。则去除该符号
				if(response.lastIndexOf("/") == response.length() - 1){
					response = response.substring(0, response.length() - 1);
				}
				//去除最后的上下文，获取外网地址
//				URLManager.URL = response.substring(0, response.lastIndexOf("/"));
//				application.setServiceUrl(URLManager.URL);
				Log.e("外网地址", URLManager.URL);
				queryInitData();
			} 
		}

		@Override
		public void onFailure(String arg0) {
			// TODO Auto-generated method stub
		}

		@Override
		public void onServiceConnected() {
			// TODO Auto-generated method stub
			action = Action.USER;
			platform.getUserInfo(packageName);
		}
		
	};
	
	/**
	 * 查询数据列表
	 */
	protected void queryUserInfoByAccount(){
		RequestInfo req = new RequestInfo();
		req.context = SearchActivity.this;
		req.requestUrl = URLManager.URL + URLManager.ACCOUNT_LOGIN_URL;
		Log.e("外网地址", req.requestUrl);
		req.params=useraccount;
		super.getDataFromServer(req, new DataCallback<String>() {
			@Override
			public void processData(String paramObject) {
				Log.e("userinfo", paramObject);
				try {
					JSONObject jsonObject = new JSONObject(paramObject);
					userInfo = (UserInfo)JsonUtil.fromJsonToModel(jsonObject, UserInfo.class);
					application.setUserInfo(userInfo);
					queryInitData();
				} catch (Exception e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void getDataFailed() {
				// 这里仅作演示，实际请求失败后怎么操作根据实际情况来看

			}

		}, SearchActivity.this);
	}
	
	OnClickListener searchClickListener = new OnClickListener() {
		@Override
		public void onClick(View v) {
			res_edit = res_name_edit.getText().toString();
			
			int professchosseid = profess_spinner.getSelectedItemPosition();
			int netypechooseid = netype_spinner.getSelectedItemPosition();
			int citychooseid = city_spinner.getSelectedItemPosition();
			if(professchosseid < 0){
				Toast.makeText(SearchActivity.this, "专业分类为空，无法查询！", Toast.LENGTH_SHORT).show();
			} else if(netypechooseid < 0){
				Toast.makeText(SearchActivity.this, "资源类型为空，无法查询！", Toast.LENGTH_SHORT).show();
			} else if(citychooseid < 0){
				Toast.makeText(SearchActivity.this, "所属地市为空，无法查询！", Toast.LENGTH_SHORT).show();
			} else {
				String professchossename = pronameList.get(professchosseid);
				String netypechoosename = netypenameList.get(netypechooseid);
				String citychoosename = citynameList.get(citychooseid);
				String citychoosevalue = cityvalueList.get(citychooseid);
				
				SharedPreferences sysInfo = getSharedPreferences("inspur_rss_info", 0);
				sysInfo.edit().putString("default_city_name",citychoosename).commit();
				sysInfo.edit().putString("default_city_vaule",citychoosevalue).commit();
				sysInfo.edit().putString("default_netype_name",netypechoosename).commit();
				sysInfo.edit().putString("default_profess_name",professchossename).commit();
				sysInfo.edit().putString("default_edit_name", res_edit).commit();
				Intent intent = new Intent(SearchActivity.this, ResListActivity.class);
				Bundle bundle = new Bundle();
				bundle.putString("searchType", "searchByInit");
				bundle.putString("resClassEnName", netypechoosename);
				bundle.putString("zh_label", res_edit);
				bundle.putString("city_id", citychoosename);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		}
	};
	
	/**
	 * 初始化查询条件
	 */
	private void queryInitData() {
		cacheService = new CacheService(this);
		String[] cache = cacheService.getCacheWithFlag(conditionKey);
		
		if(cache == null || "".equals(cache[1]) || "-1".equals(cache[1]) || "1".equals(cache[0])){
			this.queryInitDataByNet();
		} else {
			existCacheFlag = true;
			parseData(cache[1]);
		}
	}
	
	/**
	 * 调用后台获取条件数据
	 */
	private void queryInitDataByNet() {
		if(cacheService == null){
			cacheService = new CacheService(this);
		}
		
		RequestInfo req = new RequestInfo();
		req.context = SearchActivity.this;
		req.requestUrl = URLManager.URL + URLManager.RES_QUERYINITCONDITION;
		
		JSONObject condition = new JSONObject();
		req.params = condition.toString();
		
		req.params="{'useraccount':'"+application.getUserInfo().getUseraccount()+"'}";
		super.getDataFromServer(req, new DataCallback<String>() {

			@Override
			public void processData(String paramObject) {
				Log.e("paramObject:", paramObject);
				parseData(paramObject);
			}

			@Override
			public void getDataFailed() {
				// 这里仅作演示，实际请求失败后怎么操作根据实际情况来看

			}

		}, SearchActivity.this);
	}	
	
	
	public void parseData(String paramObject){
		try {
			professList.clear();
			citysList.clear();
			netypesList.clear();
			pronameList.clear();
			provalueList.clear();
			netypenameList.clear();
			netypevalueList.clear();
			citynameList.clear();
			cityvalueList.clear();
			JSONObject jsonObj = new JSONObject(paramObject);
			JSONArray diagramArray = jsonObj.getJSONArray("diagramList");
			if(diagramArray != null && diagramArray.length() >0){
				for(int i = 0; i < diagramArray.length(); i++){
					JSONObject diagramObj = diagramArray.getJSONObject(i);
					String [] strs =new String[3]; 
					strs[0] = diagramObj.getString("resClassDiagramID");
					strs[1] = diagramObj.getString("resClassDiagramCnName");
					strs[2] = diagramObj.getString("resClassDiagramEnName");
					professList.add(strs);
				}
			}
			JSONArray cityArray = jsonObj.getJSONArray("cityList");
			if(cityArray != null && cityArray.length() >0){
				for(int i = 0; i < cityArray.length(); i++){
					JSONObject cityObj = cityArray.getJSONObject(i);
					String [] strs =new String[2]; 
					strs[0] = cityObj.getString("int_id");
					strs[1] = cityObj.getString("zh_label");
					citysList.add(strs);
				}
			}
			JSONArray netypeArray = jsonObj.getJSONArray("classList");
			Log.e("netypeArray", netypeArray.length() + "");
			if(netypeArray != null && netypeArray.length() >0){
				for(int i = 0; i < netypeArray.length(); i++){
					JSONObject netypeObj = netypeArray.getJSONObject(i);
					String [] strs =new String[3]; 
					strs[0] = netypeObj.getString("resClassDiagramType");
					strs[1] = netypeObj.getString("resClassEnName");
					strs[2] = netypeObj.getString("resClassCnName");
					netypesList.add(strs);
				}
			}
			String modifyRes = jsonObj.getString("modifyRes");
			if(!modifyRes.equals("0")){
				modifyRes = "," + modifyRes + ",";
			}
			application.setModifyRes(jsonObj.getString("modifyRes"));
			Log.e("modifyRes", modifyRes);
			if(existCacheFlag){
				cacheService.updateCache(conditionKey, paramObject);
			} else {
				cacheService.saveCache(conditionKey, paramObject);
				existCacheFlag = true;
			}
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		initView();
	}
	
	private void initView() {
		
		for (int i = 0; i < professList.size(); i++) {
			String[] strs = new String[2];
			strs = professList.get(i);
			pronameList.add(strs[0]);
			provalueList.add(strs[1]);
		}
		initProfessSpinner();// 专业列表初始化
		for (int i = 0; i < netypesList.size(); i++) {// 专业与网元类型相关联，对各个专业关联网元类型予以区分
			String[] strs = new String[3];
			strs = netypesList.get(i);
			if (strs[0].equalsIgnoreCase(pronameList.get(0))) {
				netypenameList.add(strs[1]);
				netypevalueList.add(strs[2]);
			}

		}
		initNetTypeSpinner();// 网元列表初始化
		String reference_city_name = "";
		String reference_city_value = "";
		for (int i = 0; i < citysList.size(); i++) {
			String[] strs = new String[2];
			strs = citysList.get(i);
			citynameList.add(strs[0]);
			cityvalueList.add(strs[1]);
			if (i == 0) {
				reference_city_name = strs[0];
				reference_city_value = strs[1];
			} else {
				reference_city_name = reference_city_name + "," + strs[0];
				reference_city_value = reference_city_value + "," + strs[1];
			}
		}
		SharedPreferences sysInfo = getSharedPreferences("inspur_rss_info", 0);
		sysInfo.edit().putString("reference_city_name", reference_city_name).commit();
		sysInfo.edit().putString("reference_city_value", reference_city_value).commit();
		initCitysSpinner();// 城市列表初始化
	}

	// 设置专业单选框
	public void initProfessSpinner() {
		// 将可选内容与ArrayAdapter连接起来
		profAdapter = new ArrayAdapter<String>(this,
				R.layout.simple_spinner_item, provalueList);
		// 设置下拉列表的风格
		profAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将adapter 添加到spinner中
		profess_spinner.setAdapter(profAdapter);
		SharedPreferences sysInfo = getSharedPreferences("inspur_rss_info", 0);
		String default_profess_name = sysInfo.getString("default_profess_name",
				"");
		int selection = 0;
		for (int i = 0; i < pronameList.size(); i++) {
			String name = pronameList.get(i);
			if (name.equals(default_profess_name)) {
				selection = i;
			}
		}
		if (selection > 0) {
			profess_spinner.setSelection(selection);
		}
		// 添加事件Spinner事件监听
		profess_spinner.setOnItemSelectedListener(profItemSelected);
		// 设置默认值
		profess_spinner.setVisibility(View.VISIBLE);
	}
		
	OnItemSelectedListener profItemSelected = new OnItemSelectedListener() {
		
		public void onItemSelected(AdapterView<?> arg0, View arg1,
				int position, long arg3) {
			// TODO Auto-generated method stub
			professSelected = provalueList.get(position);
			// 将网元列表内容与选择的专业对应
			netypenameList.clear();
			netypevalueList.clear();
			netypeSelected = "";
			for (int i = 0; i < netypesList.size(); i++) {
				String[] strs = new String[3];
				strs = netypesList.get(i);
				if (strs[0].equalsIgnoreCase(pronameList.get(position))) {
					netypenameList.add(strs[1]);
					netypevalueList.add(strs[2]);
				}
			}
			if(arg1 != null){
				TextView tv = (TextView) arg1;
				tv.setTextColor(getResources().getColor(R.color.black));
			}
			initNetTypeSpinner();
		}
		
		public void onNothingSelected(AdapterView<?> arg0) {
			// TODO Auto-generated method stub
			
		}
		
	};

	private void initNetTypeSpinner() {
		
		// 将可选内容与ArrayAdapter连接起来
		netTypeAdapter = new ArrayAdapter<String>(this,
				R.layout.simple_spinner_item, netypevalueList);
		// 设置下拉列表的风格
		netTypeAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将adapter 添加到spinner中
		netype_spinner.setAdapter(netTypeAdapter);
		SharedPreferences sysInfo = getSharedPreferences("inspur_rss_info", 0);
		String default_netype_name = sysInfo.getString("default_netype_name",
				"");
		int selection = 0;
		for (int i = 0; i < netypenameList.size(); i++) {
			String name = netypenameList.get(i);
			if (name.equals(default_netype_name)) {
				selection = i;
			}
		}
		if (selection > 0) {
			netype_spinner.setSelection(selection);
		}
		// 添加事件Spinner事件监听
		// spinner.setOnItemSelectedListener(new SpinnerSelectedListener());
		netype_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				try {
					// TODO Auto-generated method stub
					netypeSelected = netypevalueList.get(arg2);
					
					TextView tv = (TextView) arg1;
//					tv.setTextColor(getResources().getColor(R.color.black));
				} catch (Exception e) {
					e.printStackTrace();
					// TODO: handle exception
				}
			}
			
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				netypeSelected = "";
			}
			
		});
		// 设置默认值
		netype_spinner.setVisibility(View.VISIBLE);
	}

	private void initCitysSpinner() {
		// 将可选内容与ArrayAdapter连接起来
		cityAdapter = new ArrayAdapter<String>(this,
				R.layout.simple_spinner_item, cityvalueList);
		// 设置下拉列表的风格
		cityAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		// 将adapter 添加到spinner中
		city_spinner.setAdapter(cityAdapter);
		// 添加事件Spinner事件监听
		// spinner.setOnItemSelectedListener(new SpinnerSelectedListener());
		// 设置默认值
		city_spinner.setVisibility(View.VISIBLE);
		SharedPreferences sysInfo = getSharedPreferences("inspur_rss_info", 0);
		String default_city_name = sysInfo.getString("default_city_name", "");
		int selection = 0;
		for (int i = 0; i < citynameList.size(); i++) {
			String name = citynameList.get(i);
			if (name.equals(default_city_name)) {
				selection = i;
			}
		}
		if (selection > 0) {
			city_spinner.setSelection(selection);
		}/*
		 * else if(citynameList.size()>0){ city_spinner.setSelection(1); }
		 */
		city_spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
			
			public void onItemSelected(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				// TODO Auto-generated method stub
				if(arg1 != null){
					TextView tv = (TextView) arg1;
					tv.setTextColor(getResources().getColor(R.color.black));
				}
				citySelected = cityvalueList.get(arg2);
			}
			
			public void onNothingSelected(AdapterView<?> arg0) {
				// TODO Auto-generated method stub
				citySelected = "";
			}
			
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		// TODO Auto-generated method stub
		switch (item.getOrder()) {
		case 0:
			this.onBackPressed();
			break;
		case 100:
			this.queryInitDataByNet();
			break;
		case 200:
			Intent intent = new Intent(SearchActivity.this, CaptureActivity.class);
			SearchActivity.this.startActivity(intent);
			break;
		default:
			break;
		}
		return false;
	}
	
	@Override
	protected void loadViewLayout() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void findViewById() {
		// TODO Auto-generated method stub
		profess_spinner = (Spinner) findViewById(R.id.profess_spinner);
		netype_spinner = (Spinner) findViewById(R.id.res_spinner);
		city_spinner = (Spinner) findViewById(R.id.city_spinner);
		res_name_edit = (EditText) findViewById(R.id.res_name_edit);
		
	}
	@Override
	protected void processLogic() {
		// TODO Auto-generated method stub

	}

	@Override
	protected void setListener() {
		// TODO Auto-generated method stub
		
	}
	
	@Override
	protected void onPause() {
		// TODO Auto-generated method stub
		if (null != platform)
			platform.unbindService();// 注销服务
		super.onPause();
	}


}
